package jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/**
 * 实现用户登录功能
 */
public class LoginDemo {
    public static void main(String[] args) {
        /*
        try(Connection conn = DBUtil.getConnection();) {
            Statement statement = conn.createStatement();
            Scanner scan = new Scanner(System.in);
            System.out.println("请输入您的用户名：");
            String username = scan.nextLine();
            System.out.println("请输入您的密码：");
            String password = scan.nextLine();
            String sql = "SELECT username,password,nickname,age FROM userinfo WHERE username = '"
                    +username+"' AND password = '"+password+"';";
            ResultSet rs = statement.executeQuery(sql);
            if (rs.next()){
                String name = rs.getString("username");
                password = rs.getString("password");
                String nickname = rs.getString("nickname");
                int age = rs.getInt("age");
                System.out.println("name:"+name+"nickname:"+nickname+"age:"+age);
            }else{
                System.out.println("用户名或密码输入错误");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
      */
        LoginUserInfo loginUserInfo = InputUtil.getInputObject(new LoginUserInfo(), "欢迎登录");
        try (Connection connection = DBUtil.getConnection()) {
            Statement statement = connection.createStatement();
            String sql = "SELECT id,username,password,nickname,age " +
                    "FROM userinfo " +
                    "WHERE username='" + loginUserInfo.getUsername() + "' " +
                    "AND password='" + loginUserInfo.getPassword() + "'";
            System.out.println(sql);
            ResultSet rs = statement.executeQuery(sql);
            if (rs.next()) {
                String nickname = rs.getString("nickname");
                System.out.println("登录成功，欢迎回来:" + nickname);
            } else {
                System.out.println("登录失败,用户名或密码不正确");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
